package com.java.example.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.java.example.entity.User;
import com.java.example.mapper.IUserMapper;
import com.java.example.model.RegisterReq;
import com.java.example.service.IUserService;
import com.java.example.util.MailUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：mmzsblog.cn
 * @description：TODO
 * @date ：2024/4/29 22:23
 */
@Service
public class UserServiceImpl implements IUserService {

    public static final Map<String, String> codeMap = new HashMap<>();

    @Resource
    private IUserMapper userMapper;
    @Resource
    private MailUtil mailUtil;

    @Override
    public Boolean sendVerificationCode(String email) {
        System.out.println(email + "的验证码生成！");
        String code = mailUtil.generateRandomSixDigit();
        codeMap.put(email, code);
        ThreadUtil.execAsync(() -> {
            ThreadUtil.sleep(60 * 1000);
            System.out.println(email + "的验证码过期！");
            codeMap.remove(email);
        });
        mailUtil.complexMail(code);
        return Boolean.TRUE;
    }


    @Override
    public void register(RegisterReq registerReq) {
        // 参数验证
        if (StrUtil.isBlank(registerReq.getEmail()) || StrUtil.isBlank(registerReq.getPassword())
                || StrUtil.isBlank(registerReq.getCode()) || StrUtil.isBlank(registerReq.getName())) {
            throw new RuntimeException("参数错误");
        }

        if (registerReq.getCode().equals(codeMap.get(registerReq.getEmail()))) {
            User user = new User();
            user.setEmail(registerReq.getEmail());
            user.setName(registerReq.getName());
            String password = registerReq.getPassword();
            user.setPassword(MD5.create().digestHex16(password));
            userMapper.insert(user);
        } else {
            throw new RuntimeException("验证码错误");
        }
    }

}
